<script setup>
import { ref, reactive } from 'vue';
import { ElSelect, ElOption, ElInput, ElButton, ElTable, ElTableColumn, ElDialog, ElForm, ElFormItem, ElMessage } from 'element-plus';
import { Search } from '@element-plus/icons-vue';
import axios from 'axios';

const props = defineProps({
    message: {
        classes: [],
        count: 0,
        studentList: [],
    },
    getData: {
        type: Function,
        default: () => { }
    }
});

var inquireValue = reactive({
    classes: '',
    name: '',
});

var studentMessage = reactive({
    id: '',
    name: '',
    classes: '',
    chinese: '',
    math: '',
    english: '',
});

const conditionalQueriesStudent = async () => {
    props.getData(true);
    try {
        const response = await axios.get('http://api.cqhx.work:8080/api/student/conditionalQueriesStudent', {
            params: {
                name: inquireValue.name,
                classes: inquireValue.classes === 'default' ? '' : inquireValue.classes,
            }
        });
        props.message.studentList = response.data;
        props.message.count = response.data.length;
    } catch (error) {
        ElMessage.error('查询失败，请重试');
        console.error(error);
    }
};

const validateScores = (chinese, math, english) => {
    const scores = [chinese, math, english];
    for (const score of scores) {
        if (isNaN(score) || score < 0 || score > 100) {
            return false;
        }
    }
    return true;
};

const validateClassFormat = (classes) => {
    const pattern = /^\d{2}级\d+班$/;
    return pattern.test(classes);
};

const update = async () => {
    if (!validateScores(parseFloat(studentMessage.chinese), parseFloat(studentMessage.math), parseFloat(studentMessage.english))) {
        ElMessage.error('成绩请输入数字，且范围为0-100');
        return;
    }

    if (!validateClassFormat(studentMessage.classes)) {
        ElMessage.error('班级格式错误');
        return;
    }

    try {
        await axios.put('http://api.cqhx.work:8080/api/student/updateStudent', {
            id: studentMessage.id,
            name: studentMessage.name,
            classes: studentMessage.classes,
            chinese: studentMessage.chinese,
            math: studentMessage.math,
            english: studentMessage.english,
        });
        ElMessage.success('修改成功');
        conditionalQueriesStudent();
        resetStudentMessage();
    } catch (error) {
        ElMessage.error('修改失败，请重试');
        console.error(error);
    }
};

const deleteOne = async (id) => {
    try {
        await axios.delete('http://api.cqhx.work:8080/api/student/deleteStudent', {
            params: { id },
        });
        ElMessage.success('删除成功');
        conditionalQueriesStudent();
    } catch (error) {
        ElMessage.error('删除失败，请重试');
        console.error(error);
    }
};

const deleteBatch = async () => {
    if (selectedRows._rawValue.value.length === 0) {
        ElMessage.warning('请至少选择一条数据');
        return;
    }

    try {
        const ids = selectedRows._rawValue.value.map(row => row.id);
        await axios.delete('http://api.cqhx.work:8080/api/student/deleteStudentBatch', {
            data: ids,
            headers: { 'Content-Type': 'application/json' },
        });
        ElMessage.success('批量删除成功');
        conditionalQueriesStudent();
    } catch (error) {
        ElMessage.error('批量删除失败，请重试');
        console.error(error);
    }
};

const increase = async () => {
    if (!validateScores(parseFloat(studentMessage.chinese), parseFloat(studentMessage.math), parseFloat(studentMessage.english))) {
        ElMessage.error('成绩请输入数字，且范围为0-100');
        return;
    }

    if (!validateClassFormat(studentMessage.classes)) {
        ElMessage.error('班级格式错误');
        return;
    }

    try {
        await axios.post('http://api.cqhx.work:8080/api/student/addStudent', {
            name: studentMessage.name,
            classes: studentMessage.classes,
            chinese: studentMessage.chinese,
            math: studentMessage.math,
            english: studentMessage.english,
        });
        ElMessage.success('新增成功');
        conditionalQueriesStudent();
        resetStudentMessage();
    } catch (error) {
        ElMessage.error('新增失败，请重试');
        console.error(error);
    }
};

const resetStudentMessage = () => {
    studentMessage.id = '';
    studentMessage.name = '';
    studentMessage.classes = '';
    studentMessage.chinese = '';
    studentMessage.math = '';
    studentMessage.english = '';
    newStudent.value = false;
    updateStudent.value = false;
};

var newStudent = ref(false);
var updateStudent = ref(false);
const selectedRows = ref([]);
</script>

<template>
    <div class='DivSubject'>
        <div class="search-container">
            <div class="search-item">
                <h3>查询班级:</h3>
                <el-select placeholder="班级" v-model="inquireValue.classes" style="width: 200px;">
                    <el-option value="default" class="ClassesOption" />
                    <el-option v-for="classes in message.classes" :value="classes" :key="classes" :label="classes"
                        class="ClassesOption" />
                </el-select>
            </div>
            <div class="search-item">
                <h3>查询学生:</h3>
                <el-input v-model="inquireValue.name" placeholder="学生姓名" style="width: 200px;" maxlength="10" clearable
                    @keyup.enter="conditionalQueriesStudent" @clear="conditionalQueriesStudent" />
            </div>
            <div class="search-item">
                <el-button type="success" @click="conditionalQueriesStudent" :icon="Search" round>查询</el-button>
            </div>
        </div>

        <div class="list-header">
            <h2>学生信息列表</h2>
            <div class="data-info">
                <span>共有 {{ message.count }} 条数据</span>
                <div class="button-group">
                        <el-button type="danger" round @click="deleteBatch">批量删除数据</el-button>
                        <el-button type="primary" round @click="newStudent = true">新增数据</el-button>
                    <el-dialog v-model="newStudent" title="新增学生" width="500">
                        <el-form :model="studentMessage">
                            <el-form-item label="请输入名字:">
                                <el-input v-model="studentMessage.name" aria-autocomplete="off" maxlength="10"
                                    :lable-width="100" />
                            </el-form-item>
                            <el-form-item label="请输入班级(xx级xx班):">
                                <el-input v-model="studentMessage.classes" aria-autocomplete="off" maxlength="10"
                                    :lable-width="100" />
                            </el-form-item>
                            <el-form-item label="请输入语文成绩:">
                                <el-input v-model="studentMessage.chinese" aria-autocomplete="off" maxlength="10"
                                    :lable-width="100" />
                            </el-form-item>
                            <el-form-item label="请输入数学成绩:">
                                <el-input v-model="studentMessage.math" aria-autocomplete="off" maxlength="10"
                                    :lable-width="100" />
                            </el-form-item>
                            <el-form-item label="请输入英语成绩:">
                                <el-input v-model="studentMessage.english" aria-autocomplete="off" maxlength="10"
                                    :lable-width="100" />
                            </el-form-item>
                            <div>
                                <el-button type="info" plain round @click="newStudent = false">
                                    取消
                                </el-button>
                                <el-button type="Success" plain round @click="increase">
                                    确定
                                </el-button>
                            </div>
                        </el-form>
                    </el-dialog>
                    </div>
            </div>
        </div>

        <div>
            <!-- height这个是改表的高度 -->
            <el-table :data="message.studentList" height="550" max-width="1200" style="width: 1000px;" border stripe
                @selection-change="(val) => { selectedRows.value = val }">
                <el-table-column type="selection" width="55" />
                <el-table-column label="id" width="120" prop="id" />
                <el-table-column label="名字" width="120" prop="name" />
                <el-table-column label="班级" width="120" prop="classes" />
                <el-table-column label="语文" width="120" prop="chinese" />
                <el-table-column label="数学" width="120" prop="math" />
                <el-table-column label="英语" width="120" prop="english" />
                <el-table-column label="总分" width="120" prop="score" sortable />
                <el-table-column label="操作" width="150">
                    <template #default="scope">
                        <el-button type="warning" plain size="small"
                            @click="() => { studentMessage.id = scope.row.id; updateStudent = true }">修改</el-button>
                        <el-button type="danger" plain size="small" @click="deleteOne(scope.row.id)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-dialog v-model="updateStudent" title="修改" width="500">
                    <el-form :model="studentMessage">
                                <!-- <el-form-item label="请输入ID:">
                                <el-input v-model="studentMessage.id" aria-autocomplete="off" maxlength="10" :lable-width="100"/>
                            </el-form-item> -->
                    <el-form-item label="请输入名字:">
                        <el-input v-model="studentMessage.name" aria-autocomplete="off" maxlength="10"
                                :lable-width="100" />
                    </el-form-item>
                    <el-form-item label="请输入班级(xx级xx班):">
                        <el-input v-model="studentMessage.classes" aria-autocomplete="off" maxlength="10"
                                :lable-width="100" />
                    </el-form-item>
                    <el-form-item label="请输入语文成绩:">
                        <el-input v-model="studentMessage.chinese" aria-autocomplete="off" maxlength="10"
                                :lable-width="100" />
                    </el-form-item>
                    <el-form-item label="请输入数学成绩:">
                        <el-input v-model="studentMessage.math" aria-autocomplete="off" maxlength="10"
                            :lable-width="100" />
                    </el-form-item>
                    <el-form-item label="请输入英语成绩:">
                        <el-input v-model="studentMessage.english" aria-autocomplete="off" maxlength="10"
                            :lable-width="100" />
                    </el-form-item>
                    <div>
                        <el-button type="info" plain round @click="updateStudent = false">
                            取消
                        </el-button>
                        <el-button type="Success" plain round @click="update">
                            确定
                        </el-button>
                    </div>
                </el-form>
            </el-dialog>
        </div>
    </div>
</template>

<style >
/* :deep(.el-table__header) {
    table-layout: fixed;
    width: 100%;
}

:deep(.el-table__body) {
    table-layout: fixed;
    width: 100%;
}

:deep(.el-table__header th),
:deep(.el-table__body td) {
    white-space: nowrap;
    text-align: center;
    overflow: hidden;
    text-overflow: ellipsis;
} */

.DivSubject {
    padding: 20px;
    margin-top: -125px;
    padding-top: 100px;
}

.search-container {
    position: fixed;
    /* 改为固定定位 */
    top: 80px;
    /* 距离顶部距离 */
    left: 320px;
    /* 距离左侧距离 */
    z-index: 1000;
    /* 确保显示在最上层 */
    background-color: #f5f7fa;
    border-radius: 20px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    display: flex;
    align-items: center;
    padding: 15px 20px;
    font-family: '仿宋';
    width: 1100px;
    /* 减去左侧边距 */
}

.search-item {
    position: relative;
    /* 相对定位 */
    display: flex;
    align-items: center;
    gap: 10px;
}

/* 第二个搜索项（查询学生） */
.search-item:nth-child(2) {
    margin-left: 150px;
    position: relative;
}

/* 第三个搜索项（查询按钮） */
.search-item:last-child {
    margin-left: 200px;
    position: relative;
}

/* ...existing code... */

.ClassesOption {
    width: 200px;
    padding: 8px 12px;
}

.ClassesOption:hover {
    background-color: rgb(154, 214, 227);
    color: #000;
}

.list-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin: 10px 0;
    padding: 10px 0;
    width: 1150px;
}

.list-header h2 {
    margin: 0;
    font-size: 20px;
    color: #2c3e50;
}

.data-info {
    display: flex;
    align-items: center;
    gap: 710px;
    /* justify-content: space-between; */
    justify-content: flex-start;
}



.count-text {
    font-size: 16px;
    color: #606266;
}

.button-group {
    display: flex;
    gap: -50px;
}


</style>